package com.sakiko.audiobook.handler;

import com.sakiko.audiobook.entity.CDCEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * projectName: com.sakiko.audiobook.handler
 *
 * @author: sakiko
 * time: 2025/10/9 20:32
 * description: 同步处理类
 */
@Component
@Slf4j
@CanalTable("album_info") // 监听表
public class AlbumInfoCdcHandler implements EntryHandler<CDCEntity> {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void insert(CDCEntity cdcEntity) {
        EntryHandler.super.insert(cdcEntity);
    }

    @Override
    public void update(CDCEntity before, CDCEntity after) {
        // 如果监听到了表数据发生了更新操作；删除缓存；
//        EntryHandler.super.update(before, after);
        System.out.println("before:\t" + before.getId());
        System.out.println("after:\t" + after.getId());
        // album:info:[1625]
        String key = "album:info:[" + after.getId() + "]";
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            System.out.println("AlbumInfoCdcHandler.update:" + e.getMessage());
            // 记录日志，落盘到数据库表！
            // 还可以引入 mq再次重试操作
        }
    }

    @Override
    public void delete(CDCEntity cdcEntity) {
        EntryHandler.super.delete(cdcEntity);
    }
}
